package com.develop.web.in.request.form.field.formatter;

import lombok.extern.slf4j.Slf4j;
import org.javamoney.moneta.Money;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import javax.money.Monetary;
import javax.money.MonetaryAmount;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Locale;

@Slf4j
@Component
public class String2MonetaryAmount implements Formatter<MonetaryAmount> {

    @Override
    public MonetaryAmount parse(String text, Locale locale) throws ParseException {
        MonetaryAmount amount = Money.zero(Monetary.getCurrency("CNY"));
        try {
            amount = Money.of(new BigDecimal(text.split(" ")[1]), text.split(" ")[0]);
        }
        catch (Exception e){
            log.error(e.toString());
        }
        return amount;
    }

    @Override
    public String print(MonetaryAmount amount, Locale locale) {
        return amount.toString();
    }
}
